package meiyunting.shiwuzhaoling.controller;

import meiyunting.shiwuzhaoling.dto.ClaimDTO;
import meiyunting.shiwuzhaoling.model.*;
import meiyunting.shiwuzhaoling.service.ClaimService;
import meiyunting.shiwuzhaoling.service.ItemService;
import meiyunting.shiwuzhaoling.service.UserService;
import meiyunting.shiwuzhaoling.service.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/claims")
public class ClaimController {

    private final ClaimService claimService;
    private final ItemService itemService;
    private final UserService userService;
    private final FileStorageService fileStorageService;

    @Autowired
    public ClaimController(ClaimService claimService, ItemService itemService, UserService userService, FileStorageService fileStorageService) {
        this.claimService = claimService;
        this.itemService = itemService;
        this.userService = userService;
        this.fileStorageService = fileStorageService;
    }

    @GetMapping("/create/{itemId}")
    public String showClaimForm(@PathVariable Long itemId, Model model) {
        Item item = itemService.findItemById(itemId);
        User currentUser = userService.getCurrentUser();
        
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        // 根据物品状态确定认领类型
        ClaimType defaultClaimType = item.getStatus() == ItemStatus.FOUND ? 
                ClaimType.CLAIM_FOUND : ClaimType.FOUND_LOST;
        
        ClaimDTO claimDTO = new ClaimDTO();
        claimDTO.setItemId(itemId);
        claimDTO.setClaimerId(currentUser.getId());
        claimDTO.setClaimType(defaultClaimType);
        
        model.addAttribute("item", item);
        model.addAttribute("claimDTO", claimDTO);
        model.addAttribute("claimType", defaultClaimType);
        
        return "claims/create";
    }

    @PostMapping("/create")
    public String createClaim(@ModelAttribute ClaimDTO claimDTO, RedirectAttributes redirectAttributes) {
        try {
            Item item = itemService.findItemById(claimDTO.getItemId());
            User claimer = userService.findById(claimDTO.getClaimerId());
            
            // 处理图片上传
            String imagePath = null;
            if (claimDTO.getImage() != null && !claimDTO.getImage().isEmpty()) {
                imagePath = fileStorageService.storeFile(claimDTO.getImage());
            }
            
            // 使用新的createClaim方法
            Claim claim = claimService.createClaim(
                item, 
                claimer, 
                claimDTO.getDescription(), 
                claimDTO.getClaimType(), 
                imagePath
            );
            
            String message = claimDTO.getClaimType() == ClaimType.CLAIM_FOUND ? 
                    "认领申请已提交，等待处理" : "找到物品的信息已提交，等待失主确认";
            redirectAttributes.addFlashAttribute("successMessage", message);
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "提交失败: " + e.getMessage());
        }
        
        return "redirect:/items/" + claimDTO.getItemId();
    }

    @GetMapping("/item/{itemId}")
    public String getClaimsByItem(@PathVariable Long itemId, Model model) {
        Item item = itemService.findItemById(itemId);
        List<Claim> claims = claimService.getClaimsByItem(item);
        
        // 添加当前用户信息
        User currentUser = userService.getCurrentUser();
        
        model.addAttribute("item", item);
        model.addAttribute("claims", claims);
        model.addAttribute("currentUser", currentUser);
        
        return "claims/item-claims";
    }

    @GetMapping("/user")
    public String getCurrentUserClaims(Model model) {
        User currentUser = userService.getCurrentUser();
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        List<Claim> claims = claimService.getClaimsByUser(currentUser);
        model.addAttribute("claims", claims);
        model.addAttribute("currentUser", currentUser);
        
        return "claims/user-claims";
    }

    @PostMapping("/{id}/status")
    public String updateClaimStatus(@PathVariable Long id, 
                                  @RequestParam ClaimStatus status,
                                  RedirectAttributes redirectAttributes) {
        try {
            Claim claim = claimService.updateClaimStatus(id, status);
            String statusMessage = status == ClaimStatus.APPROVED ? "已批准" : "已拒绝";
            redirectAttributes.addFlashAttribute("successMessage", "申请" + statusMessage);
            return "redirect:/claims/item/" + claim.getItem().getId();
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "更新状态失败: " + e.getMessage());
            return "redirect:/claims/" + id;
        }
    }
    
    @PostMapping("/{id}/approve-complete")
    public String approveClaimAndCompleteItem(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            Claim claim = claimService.approveClaimAndCompleteItem(id);
            
            String message = claim.getClaimType() == ClaimType.CLAIM_FOUND ? 
                    "认领已批准，物品已完成交接" : "已确认找到物品，流程已完成";
            
            redirectAttributes.addFlashAttribute("successMessage", message);
            return "redirect:/claims/item/" + claim.getItem().getId();
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "处理失败: " + e.getMessage());
            return "redirect:/claims/" + id;
        }
    }

    @GetMapping("/{id}")
    public String getClaimDetail(@PathVariable Long id, Model model) {
        Claim claim = claimService.getClaimById(id);
        model.addAttribute("claim", claim);
        
        // 添加当前用户信息
        User currentUser = userService.getCurrentUser();
        model.addAttribute("currentUser", currentUser);
        
        return "claims/claim-detail";
    }
} 